/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package persistence;

import entityBeans.Sex;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import entityBeans.Occurrenceelement;
import java.util.ArrayList;
import java.util.List;
import persistence.exceptions.NonexistentEntityException;
/**
 *
 * @author allankv
 */
public class SexJpaController {

    public SexJpaController() {
        emf = Persistence.createEntityManagerFactory("bdd-javaPU");
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }
    public Sex save(Sex sex) {
        Sex aux = findSex(sex.getSex());
        if(aux==null){
            return create(sex);
        } else
            return aux;
    }

    public Sex create(Sex sex) {
        Sex r = null;
        if (sex.getOccurrenceelementList() == null) {
            sex.setOccurrenceelementList(new ArrayList<Occurrenceelement>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            List<Occurrenceelement> attachedOccurrenceelementList = new ArrayList<Occurrenceelement>();
            for (Occurrenceelement occurrenceelementListOccurrenceelementToAttach : sex.getOccurrenceelementList()) {
                occurrenceelementListOccurrenceelementToAttach = em.getReference(occurrenceelementListOccurrenceelementToAttach.getClass(), occurrenceelementListOccurrenceelementToAttach.getIdoccurrenceelement());
                attachedOccurrenceelementList.add(occurrenceelementListOccurrenceelementToAttach);
            }
            sex.setOccurrenceelementList(attachedOccurrenceelementList);
            r = em.merge(sex);
            for (Occurrenceelement occurrenceelementListOccurrenceelement : sex.getOccurrenceelementList()) {
                Sex oldSexOfOccurrenceelementListOccurrenceelement = occurrenceelementListOccurrenceelement.getSex();
                occurrenceelementListOccurrenceelement.setSex(sex);
                occurrenceelementListOccurrenceelement = em.merge(occurrenceelementListOccurrenceelement);
                if (oldSexOfOccurrenceelementListOccurrenceelement != null) {
                    oldSexOfOccurrenceelementListOccurrenceelement.getOccurrenceelementList().remove(occurrenceelementListOccurrenceelement);
                    oldSexOfOccurrenceelementListOccurrenceelement = em.merge(oldSexOfOccurrenceelementListOccurrenceelement);
                }
            }
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
        return r;
    }

    public void edit(Sex sex) throws NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Sex persistentSex = em.find(Sex.class, sex.getIdsex());
            List<Occurrenceelement> occurrenceelementListOld = persistentSex.getOccurrenceelementList();
            List<Occurrenceelement> occurrenceelementListNew = sex.getOccurrenceelementList();
            List<Occurrenceelement> attachedOccurrenceelementListNew = new ArrayList<Occurrenceelement>();
            for (Occurrenceelement occurrenceelementListNewOccurrenceelementToAttach : occurrenceelementListNew) {
                occurrenceelementListNewOccurrenceelementToAttach = em.getReference(occurrenceelementListNewOccurrenceelementToAttach.getClass(), occurrenceelementListNewOccurrenceelementToAttach.getIdoccurrenceelement());
                attachedOccurrenceelementListNew.add(occurrenceelementListNewOccurrenceelementToAttach);
            }
            occurrenceelementListNew = attachedOccurrenceelementListNew;
            sex.setOccurrenceelementList(occurrenceelementListNew);
            sex = em.merge(sex);
            for (Occurrenceelement occurrenceelementListOldOccurrenceelement : occurrenceelementListOld) {
                if (!occurrenceelementListNew.contains(occurrenceelementListOldOccurrenceelement)) {
                    occurrenceelementListOldOccurrenceelement.setSex(null);
                    occurrenceelementListOldOccurrenceelement = em.merge(occurrenceelementListOldOccurrenceelement);
                }
            }
            for (Occurrenceelement occurrenceelementListNewOccurrenceelement : occurrenceelementListNew) {
                if (!occurrenceelementListOld.contains(occurrenceelementListNewOccurrenceelement)) {
                    Sex oldSexOfOccurrenceelementListNewOccurrenceelement = occurrenceelementListNewOccurrenceelement.getSex();
                    occurrenceelementListNewOccurrenceelement.setSex(sex);
                    occurrenceelementListNewOccurrenceelement = em.merge(occurrenceelementListNewOccurrenceelement);
                    if (oldSexOfOccurrenceelementListNewOccurrenceelement != null && !oldSexOfOccurrenceelementListNewOccurrenceelement.equals(sex)) {
                        oldSexOfOccurrenceelementListNewOccurrenceelement.getOccurrenceelementList().remove(occurrenceelementListNewOccurrenceelement);
                        oldSexOfOccurrenceelementListNewOccurrenceelement = em.merge(oldSexOfOccurrenceelementListNewOccurrenceelement);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = sex.getIdsex();
                if (findSex(id) == null) {
                    throw new NonexistentEntityException("The sex with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Sex sex;
            try {
                sex = em.getReference(Sex.class, id);
                sex.getIdsex();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The sex with id " + id + " no longer exists.", enfe);
            }
            List<Occurrenceelement> occurrenceelementList = sex.getOccurrenceelementList();
            for (Occurrenceelement occurrenceelementListOccurrenceelement : occurrenceelementList) {
                occurrenceelementListOccurrenceelement.setSex(null);
                occurrenceelementListOccurrenceelement = em.merge(occurrenceelementListOccurrenceelement);
            }
            em.remove(sex);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Sex> findSexEntities() {
        return findSexEntities(true, -1, -1);
    }

    public List<Sex> findSexEntities(int maxResults, int firstResult) {
        return findSexEntities(false, maxResults, firstResult);
    }

    private List<Sex> findSexEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Sex.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Sex findSex(String q) {
        Query query= getEntityManager().createNamedQuery("Sex.findBySex");
        query.setParameter("sex",q);

        return query.getResultList().isEmpty()?null:(Sex)query.getResultList().get(0);
    }

    public Sex findSex(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Sex.class, id);
        } finally {
            em.close();
        }
    }

    public int getSexCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Sex> rt = cq.from(Sex.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }

}
